import { constantRoutes } from '@/router'
import { getAuthMenu } from '@/api/system/login.api'
import Layout from '@/layout'

const permission = {
    state: {
        routes: [],
        addRoutes: []
    },
    mutations: {
        SET_ROUTES: (state, routes) => {
            state.addRoutes = routes
            state.routes = constantRoutes.concat(routes)
        },
    },
    actions: {
        generateRoutes({commit}) {
            return new Promise(resolve => {
                getAuthMenu().then(res => {
                    const sdata = JSON.parse(JSON.stringify(res.data))
                    const sidebarRoutes = filterAsyncRouter(sdata)
                    commit('SET_ROUTES', sidebarRoutes)
                    resolve(sidebarRoutes)
                })
            })
        }
    }
}


export function filterAsyncRouter(routes) {
    const res = [];
    routes.forEach(route => {
        const temp = {
          path: '',
          // hidden: true,
          component: Layout,
          name: route.name,
          code: route.code,
          children: []
        }
        route.children.forEach(item=>{
          temp.children.push({
            path: item.path,
            // hidden: true,
            component: () => import(`@/views/${item.code}/index.vue`),
            // component: () => import('@/modules/views/proxy_api/index.vue'),
            name: item.name,
          })
        })
        res.push(temp)
      })
    return res;
}

export const loadView = (view) => { // 路由懒加载
    return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission